// eslint-disable-next-line import/no-extraneous-dependencies
import { Request, Response } from 'express';
import { parse } from 'url';
import mockjs from 'mockjs';
import { PermissionTableListItem, PermissionTableListParams } from '@/pages/ums/permission/permissionData';

// mock tableListDataSource
const genList = () => {
    const tableListDataSource: PermissionTableListItem[] = mockjs.mock({
        'list|100': [{
            permissionId: /\d{5,10}/,
            parentId: /\d{5,10}/,
            permissionName: '@word',
            authority: '@word',
            icon: '@word',
            permissionType: '@integer(0,2)',
            routePath: '@word',
            component: '@word',
            isOuter: '@integer(0,1)',
            sort: '@integer(0,10)',
            status: '@integer(0,1)',
            remark: '@word',
            deleteStatus: '@integer(0,1)',
            createTime: '@datetime',
            creator: '@word',
            updateTime: '@datetime',
            modifier: '@word',
        }],
    }).list;
    tableListDataSource[0].children = mockjs.mock({
        'list|2': [{
            permissionId: /\d{5,10}/,
            parentId: /\d{5,10}/,
            permissionName: '@word',
            authority: '@word',
            icon: '@word',
            permissionType: '@integer(0,2)',
            routePath: '@word',
            component: '@word',
            isOuter: '@integer(0,1)',
            sort: '@integer(0,10)',
            status: '@integer(0,1)',
            remark: '@word',
            deleteStatus: '@integer(0,1)',
            createTime: '@datetime',
            creator: '@word',
            updateTime: '@datetime',
            modifier: '@word',
        }],
    }).list
    return tableListDataSource;
};

let tableListDataSource = genList();

/**
 * 查询列表权限
 */
function queryPermission(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { current = 1, pageSize = 10 } = req.query;
    const params = (parse(realUrl, true).query as unknown) as PermissionTableListParams;

    let dataSource = [...tableListDataSource].slice(
        ((current as number) - 1) * (pageSize as number),
        (current as number) * (pageSize as number),
    );
    if(params.sorter){
        const sorter = JSON.parse(params.sorter as any);
        if (sorter) {
            dataSource = dataSource.sort((prev, next) => {
                let sortNumber = 0;
                Object.keys(sorter).forEach((key) => {
                    if (sorter[key] === 'descend') {
                        if (prev[key] - next[key] > 0) {
                            sortNumber += -1;
                        } else {
                            sortNumber += 1;
                        }
                        return;
                    }
                    if (prev[key] - next[key] > 0) {
                        sortNumber += 1;
                    } else {
                        sortNumber += -1;
                    }
                });
                return sortNumber;
            });
        }
    }
    if (params.filter) {
        const filter = JSON.parse(params.filter as any) as {
            [key: string]: string[];
        };
        if (Object.keys(filter).length > 0) {
            dataSource = dataSource.filter((item) => {
                return Object.keys(filter).some((key) => {
                    if (!filter[key]) {
                        return true;
                    }
                    if (filter[key].includes(`${item[key]}`)) {
                        return true;
                    }
                    return false;
                });
            });
        }
    }

    const result = {
        data: dataSource,
        total: tableListDataSource.length,
        success: true,
        pageSize,
        current: parseInt(`${params.currentPage}`, 10) || 1,
    };

    return res.json(result);
}

/**
 * 获取权限
 */
function getPermission(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { id } = req.params;
    let data;
    if(id){
        data = tableListDataSource.find((item) => item.permissionId && item.permissionId.toString()===id.toString());
    }

    const result = {
        data,
        success: true,
    };

    return res.json(result);
}

/**
 * 新增权限
 */
function addPermission(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const data = req.body as PermissionTableListItem;
        data.permissionId = mockjs.mock(/\d{5,10}/);

    if(data){
        tableListDataSource.splice(0,0,data);
    }

    const result = {
        success: true,
    };
    return res.json(result);
}

/**
 * 更新权限
 */
function updatePermission(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { id } = req.params;
    const params = req.body as PermissionTableListItem;
    if(id && params){
        const data: PermissionTableListItem|undefined = tableListDataSource.find((item) => item.permissionId && item.permissionId.toString()===id.toString());
        if(data){
            Object.assign(
                data,
                params
            )
        }
    }

    const result = {
        success: true,
    };
    return res.json(result);

}

/**
 * 删除权限
 */
function deletePermission(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { id } = req.params;
    tableListDataSource = tableListDataSource.filter((item)=>item.permissionId!==id);

    const result = {
        success: true,
    };

    return res.json(result);
}

/**
 * 批量删除权限
 */
function batchDeletePermission(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { ids } = req.body;
    if(ids && ids.length){
        tableListDataSource = tableListDataSource.filter((item)=>
            item.permissionId && ids.indexOf(item.permissionId)===-1
        );
    }

    const result = {
        success: true,
    };

    return res.json(result);
}


/**
 * 更新按钮权限
 * @param params
 */
export async function updatePermissionButtons(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }

    const result = {
        success: true,
    };

    return res.json(result);
}


export default {
    'GET /api/ums/permission': queryPermission,
    'GET /api/ums/permission/:id': getPermission,
    'POST /api/ums/permission': addPermission,
    'PUT /api/ums/permission/:id': updatePermission,
    'DELETE /api/ums/permission/:id': deletePermission,
    'DELETE /api/ums/permission': batchDeletePermission,
    'POST /api/ums/permission/buttons': updatePermissionButtons,
};
